package com.palm.platform.controller;

import com.palm.core.util.CollectionUtil;
import com.palm.core.util.StringUtil;
import com.palm.platform.domain.Branch;

import org.noear.solon.core.handle.Result;
import com.palm.core.data.PageResult;
import com.palm.core.anno.Auth;
import org.noear.solon.annotation.*;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.noear.solon.validation.annotation.HttpPart;
import org.noear.solon.validation.annotation.NoRepeatSubmit;
import org.noear.solon.validation.annotation.Valid;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* 部门管理
*
* generated by palmboot
**/
@Auth
@Controller
@Mapping("branch")
public class BranchController{
    @Db
    SqlToyLazyDao dao;

    @Valid
    @NoRepeatSubmit(HttpPart.body)
    @Note("新增部门管理")
    @Mapping("add")
    public Result add(Branch branch){
        if(branch.getPid()==null){
            branch.setPid(0L);//默认的父级sn
        }
        Map<String,Object> params=new HashMap<>();
        params.put("pid",branch.getPid());
        String maxSn=(String)dao.getSingleValue("select max(sn) from t_branch where pid=:pid",params);
        String sn="";
        if(StringUtil.isEmpty(maxSn)){
            String psn=(String)dao.getSingleValue("select sn from t_branch where id=:pid",params);
            sn=psn+"0001";
        }else{
            sn=StringUtil.integerAdd(maxSn,"1");
        }
        branch.setSn(sn);
//        Result result = ValidatorManager.validateOfEntity(branch);
//        if(result.getCode()!=Result.SUCCEED_CODE){
//            return result;
//        }
        dao.save(branch);
        return Result.succeed();
    }

    @Note("删除部门管理")
    @Mapping("delete")
    public Result delete(List<Branch> branchs){
        // dao.loadAll(branchs);
        dao.deleteAll(branchs);
        return Result.succeed();
    }

    @Valid
    @Note("更新部门管理")
    @Mapping("save")
    public Result save(Branch branch){
        dao.update(branch);
        return Result.succeed();
    }

    @Note("获取部门管理")
    @Mapping("detail")
    public Result<Branch> detail(Branch query){
       Branch branch=dao.load(query);
       return Result.succeed(branch);
    }

    @Note("获取部门管理列表")
    @Mapping("list")
    public Result<List<Branch>> list(Branch query){
        List<Branch> result = dao.findBySql("branch_list",query);
        return PageResult.succeed(result);
    }
    @Note("获取部门管理列表")
    @Mapping("list_tree")
    public Result<List<Branch>> listTree(Branch query){
        List<Branch> result = dao.findBySql("branch_list",query);
       // Utils.toKeyMap()
        List<Branch> resultTree = CollectionUtil.toTree(result,Branch::getId,Branch::getPid,Branch::getChildren,0L);
        return PageResult.succeed(resultTree);
    }
}
